import json

from sparkai.llm.llm import ChatSparkLLM
from sparkai.core.messages import ChatMessage

from llm.SystemConfig import SystemConfig


def get_response(message):
    from sparkai.log.logger import logger
    # logger.setLevel("debug")
    from sparkai.core.callbacks import StdOutCallbackHandler
    messages = [{'role': 'user',
                 'content': message}]
    spark = ChatSparkLLM(
        spark_api_url=SystemConfig().SPARK_API_URL,
        spark_app_id=SystemConfig().SPARK_APP_ID,
        spark_api_key=SystemConfig().SPARK_API_KEY,
        spark_api_secret=SystemConfig().SPARK_API_SECRET,
        spark_llm_domain=SystemConfig().SPARK_LLM_DOMAIN,
        streaming=True,
        max_tokens=1024,
    )
    messages = [
        ChatMessage(
            role="user",
            content=messages[0]['content']

        )]

    a = spark.stream(messages)
    content = ""  # 把数据进行累加
    for message in a:
        content += message.content
        yield "data: " + json.dumps({"type": "message", "content": message.content}, ensure_ascii=False) + "\n\n"
        # print(message)
